let storage = bui.storage();
let language
let translate
loader.define(function (require, exports, module, global) {
    let pageview = {
        init() {
            language = storage.get("language", 0)
            translate = global.translate
            if (!language) {
                language = 'chinese_simplified'
            }

            try {
                translate.selectLanguageTag.show = false;
                translate.ignore.id.push('languageContent')
                let curLanguage = translate.language.getCurrent()
                if (curLanguage !== language) {
                    translate.changeLanguage(language)
                }
                translate.execute();
            }catch (e) {
                console.log("切换语言报错")
            }
            let languageArr = storage.get('languageArr',0)
            let html = ''
            let html2 = '<select class="languageSelect" id="languageSelectId">\n'
            if (language !== 'chinese_simplified' && language !== 'english') {
                languageArr.forEach(lan => {
                    if (lan.id === language) {
                        html += '<span class="language" id="'+lan.id+'">'+lan.name+'</span>|'
                    } else {
                        html2 += '<option value="'+lan.id+'">'+lan.name+'</option>'
                    }
                })
            } else {
                languageArr.forEach(lan => {
                    html2 += '<option value="'+lan.id+'">'+lan.name+'</option>'
                })
            }
            html+= '<span class="language" id="english">English</span>|<span class="language" id="chinese_simplified">简体中文</span>'
            router.$("#languageContent").html(html + html2 + "</select>")

            router.$(".language").click(function () {
                let selectId = $(this).attr('id')
                if (selectId !== language) {
                    storage.set("language", selectId)
                    location.reload()
                }
            })
            router.$("#languageSelectId").val("");
            router.$("#languageSelectId").change(function () {
                let selectId = $(this).val()
                if (selectId !== language) {
                    storage.set("language", selectId)
                    location.reload()
                }
            })

            let uiLoading = bui.loading({
                appendTo:"#loadingMy",
                width: 40,
                height: 40,
                opacity: 0.5,
                text:"提交中。。。",
                autoClose: false,
                callback: function (argument) {
                }
            });

            let passwordStatus = false, passwordConfStatus = false, emailStatus = false
            let imgStr;
            let user = storage.get("user", 0)
            let errMsg = storage.get("bindErrMsg", 0)
            if (errMsg) {
                bui.alert(errMsg)
                storage.set("bindErrMsg", null)
            }

            if (user) {
                router.$("#avater").attr("src", user.avatar)
                router.$("#userName").html(user.nickName)
                router.$("#accountStr").html("账号：" + user.userName)
                router.$("#emailStr").html("邮箱 ：" + user.email)
            }

            // 自定义居中弹出框
            let uploadQrcodedialog = bui.dialog({
                id: "#uploadQrcodedialog",
                height: 300,
                // mask: false,
                callback: function(e) {
                    let cla = router.$(e.target).attr('class')
                    if (cla.indexOf('blue') > -1) {
                        if (imgStr) {
                            uiLoading.show()
                            //加载新闻通知栏
                            bui.ajax({
                                url: global.api.alterQrcode,
                                data: {qrcode: imgStr, userId: user.userId},
                                method: "POST",
                            }).then(function(res){
                                if (res.code == '200') {
                                    user.qrcode = global.api.baseurl + "profile/58Upload/user/" + imgStr
                                    storage.set("user", user)
                                    bui.alert('二维码修改成功')
                                } else {
                                    bui.confirm({
                                        "title": "",
                                        "height": 460,
                                        "content": '<div class="bui-box-center"><div><h3>二维码修改失败</h3></div></div>',
                                        "buttons": [{ name: "确定", className: "primary-reverse" }],
                                        callback:function(){
                                            this.close();
                                            uploadQrcodedialog.open()
                                        }
                                    });
                                }
                                uiLoading.stop()
                            })
                        } else {
                            bui.confirm({
                                "title": "",
                                "height": 460,
                                "content": '<div class="bui-box-center"><div><h3>未上传二维码图片</h3></div></div>',
                                "buttons": [{ name: "确定", className: "primary-reverse" }],
                                callback:function(){
                                    this.close();
                                    uploadQrcodedialog.open()
                                }
                            });
                        }
                    }
                }
            });
            // 自定义居中弹出框
            let alterPwdDialog = bui.dialog({
                id: "#alterPwdDialog",
                height: 300,
                // mask: false,
                callback: function(e) {
                    let cla = router.$(e.target).attr('class')
                    if (cla.indexOf('blue') > -1) {
                        if (passwordStatus && passwordConfStatus) {
                            uiLoading.show()
                            //加载新闻通知栏
                            bui.ajax({
                                url: global.api.alterUserPwd,
                                data: {password: password.value(), userId: user.userId},
                                method: "POST",
                            }).then(function(res){
                                if (res.code == '200') {
                                    bui.alert('密码修改成功')
                                } else {
                                    bui.confirm({
                                        "title": "",
                                        "height": 460,
                                        "content": '<div class="bui-box-center"><div><h3>密码修改失败</h3></div></div>',
                                        "buttons": [{ name: "确定", className: "primary-reverse" }],
                                        callback:function(){
                                            this.close();
                                            alterPwdDialog.open()
                                        }
                                    });
                                }
                                uiLoading.stop()
                            })
                        } else {
                            bui.confirm({
                                "title": "",
                                "height": 460,
                                "content": '<div class="bui-box-center"><div><h3>密码不符合规则</h3></div></div>',
                                "buttons": [{ name: "确定", className: "primary-reverse" }],
                                callback:function(){
                                    this.close();
                                    alterPwdDialog.open()
                                }
                            });
                            if (!passwordStatus) {
                                router.$("#passwordTs").html("密码只能4-18位")
                            }
                            if (!passwordConfStatus) {
                                router.$("#passwordConTs").html("两次密码需要保持一致")
                            }
                        }
                    }
                }
            });
            // 自定义居中弹出框
            let alterEmailDialog = bui.dialog({
                id: "#alterEmailDialog",
                height: 300,
                // mask: false,
                callback: function(e) {
                    let cla = router.$(e.target).attr('class')
                    if (cla.indexOf('blue') > -1) {
                        if (emailStatus) {
                            uiLoading.show()
                            //加载新闻通知栏
                            bui.ajax({
                                url: global.api.alterUserEmail,
                                data: {email: email.value(), userId: user.userId},
                                method: "POST",
                            }).then(function(res){
                                if (res.code == '200') {
                                    router.$("#emailStr").html("邮箱 ：" + email.value())
                                    user.email = email.value()
                                    storage.set('user', user)
                                    bui.alert('邮箱修改成功')
                                } else {
                                    bui.confirm({
                                        "title": "",
                                        "height": 460,
                                        "content": '<div class="bui-box-center"><div><h3>'+res.msg+'</h3></div></div>',
                                        "buttons": [{ name: "确定", className: "primary-reverse" }],
                                        callback:function(){
                                            this.close();
                                            alterEmailDialog.open()
                                        }
                                    });
                                }
                                uiLoading.stop()
                            })
                        } else {
                            bui.confirm({
                                "title": "",
                                "height": 460,
                                "content": '<div class="bui-box-center"><div><h3>邮箱为空，或者不符合规则</h3></div></div>',
                                "buttons": [{ name: "确定", className: "primary-reverse" }],
                                callback:function(){
                                    this.close();
                                    alterEmailDialog.open()
                                }
                            });
                        }
                    }
                }
            });

            // 密码显示或者隐藏
            let password = bui.input({
                id: "#passwordInput",
                iconClass: ".icon-eye",
                onInput: function(e) {
                    e.target.value = e.target.value.trim()
                    // 注册的时候校验只能4-18位密码
                    let rule = /^[a-zA-Z0-9_-]{4,18}$/;
                    if (!rule.test(e.target.value)) {
                        passwordStatus = false
                        router.$("#passwordTs").html("密码只能4-18位")
                        return false;
                    } else {
                        passwordStatus = true
                        router.$("#passwordTs").html("")
                    }
                    return true;
                },
                callback: function(e) {
                    //切换类型
                    this.toggleType();
                    //
                    router.$(e.target).toggleClass("active")
                }
            })
            // 邮箱
            let email = bui.input({
                id: "#emailInput",
                showIcon: false,
                onInput: function(e) {
                    let rule = /^([a-zA-Z\d][\w-]{2,})@(\w{2,})\.([a-z]{2,})(\.[a-z]{2,})?$/
                    if (e.target.value) {
                        if (!rule.test(e.target.value)) {
                            emailStatus = false
                            router.$("#emailTs").html("邮箱格式不对")
                            return false;
                        } else {
                            emailStatus = true
                            router.$("#emailTs").html("")
                        }
                    } else {
                        emailStatus = false
                        router.$("#emailTs").html("邮箱不可为空")
                        return false;
                    }

                    return true;
                }
            })
            bui.input({
                id: "#passwordConfirm",
                iconClass: ".icon-eye",
                onInput: function(e){
                    e.target.value = e.target.value.trim()
                },
                onBlur: function(e) {
                    let val = password.value();
                    if (val !== e.target.value) {
                        passwordConfStatus = false
                        router.$("#passwordConTs").html("两次密码需要保持一致")
                    } else {
                        passwordConfStatus = true
                        router.$("#passwordConTs").html("")
                    }
                    return true;
                },
                callback: function(e) {
                    //切换类型
                    this.toggleType();
                    //
                    router.$(e.target).toggleClass("active")
                }
            })

            router.$("#bind").click(function () {
                //绑定微信
                if (isWeiXin()) {
                    location.href = global.api.gzhAuthorBind + "?userId=" + user.userId
                } else {
                    location.href = global.api.htmlAuthorBind + "?userId=" + user.userId
                }
            })
            router.$("#loginout").click(function () {
                storage.clear()
                let languageArr = [
                    {
                        id: 'russian',
                        name: 'Русский язык'
                    },
                    {
                        id: 'indonesian',
                        name: 'bahasa indonesia'
                    },
                    {
                        id: 'arabic',
                        name: 'بالعربية'
                    },
                    {
                        id: 'korean',
                        name: '한국어'
                    },
                    {
                        id: 'czech',
                        name: 'Čeština'
                    },
                    {
                        id: 'vietnamese',
                        name: 'Tiếng Việt'
                    }
                ]
                storage.set('languageArr', languageArr)
                router.replace({url: "pages/mainIndex/mainIndex.html"});
            })
            router.$("#uoloadQrcode").click(function () {
                imgStr = ""
                router.$("#picK").empty()
                if (user.qrcode) {
                    router.$("#btnUpload").hide()
                    $uploadBtn.show()
                    $uploadBtn.html(templatePhotoDefault(user.qrcode))
                }
                uploadQrcodedialog.open()
            })
            router.$("#alterPwd").click(function () {
                passwordStatus = false
                passwordConfStatus = false
                router.$("#password").val('')
                router.$("#passwordCon").val('')
                alterPwdDialog.open()
            })

            router.$("#alterEmail").click(function () {
                emailStatus = false
                router.$("#email").val('')
                alterEmailDialog.open()
            })

            router.$("#history").click(function () {
                router.load({url: "pages/history/history.html"});
            })

            // 拍照上传
            let $facePhoto = router.$("#buiPhoto");
            let $uploadBtn = router.$("#picK");
            let uiUpload = bui.upload({
                showProgress: true,
                // needNative: false
            });
            // 上拉菜单 js 初始化:
            bui.actionsheet({
                trigger: "#btnUpload",
                buttons: [{ name: "拍照上传", value: "camera" }, { name: "从相册选取", value: "photo" }],
                callback: function(e) {
                    let ui = this;
                    let val = router.$(e.target).attr("value");
                    switch (val) {
                        case "camera":
                            ui.hide();
                            uiUpload.add({
                                "from": "camera",
                                // "needCompress": true, // 1.5.3新增压缩
                                // "width": 300,
                                "destinationType": "file", //  file | blob | data
                                "onSuccess": function(val, data) {
                                    // 直接调用start上传图片
                                    this.start({
                                        url: global.api.userPicUpload,
                                        data: {
                                            file: this.data().file
                                        },
                                        onSuccess: function(data) {
                                            // bui.alert(data);
                                            if (data.code == '200') {
                                                imgStr = data.data.image
                                                router.$("#btnUpload").hide()
                                                $uploadBtn.show()
                                                $uploadBtn.html(templatePhoto(global.api.baseurl + "profile/58Upload/user/" + data.data.image, uiUpload))
                                            } else {
                                                bui.alert(data.msg)
                                            }
                                        },
                                        onFail: function(data) {
                                            bui.alert("图片上传失败！")
                                        },
                                    })
                                }
                            })
                            break;
                        case "photo":
                            ui.hide();
                            uiUpload.add({
                                "from": "",
                                "onSuccess": function(val, data) {
                                    this.start({
                                        url: global.api.userPicUpload,
                                        data: {
                                            file: this.data().file
                                        },
                                        onSuccess: function(data) {
                                            // bui.alert(data);
                                            if (data.code == '200') {
                                                imgStr = data.data.image
                                                router.$("#btnUpload").hide()
                                                $uploadBtn.show()
                                                $uploadBtn.html(templatePhoto(global.api.baseurl + "profile/58Upload/user/" + data.data.image, uiUpload))
                                            } else {
                                                bui.alert(data.msg)
                                            }
                                        },
                                        onFail: function(data) {
                                            bui.alert("图片上传失败！")
                                        },
                                    })
                                }
                            })
                            break;
                        case "cancel":
                            ui.hide();
                            break;
                    }
                }
            })

            // 删除图片文件
            $facePhoto.on("click", ".icon-removefill", function(e) {
                var $item = router.$(this).parents(".span1");
                var index = $item.attr("data-index");
                var name = $item.attr("data-name");

                // 删除对应的上传数据
                uiUpload.remove(name);
                // 删除dom显示
                // $item.remove();
                $item.empty();
                // $("#picK").empty()
                e.stopPropagation();
                router.$("#btnUpload").show()
                $uploadBtn.hide()
                imgStr = ""
            })
        }
    }
    // 初始化
    pageview.init();

    // 输出模块
    return pageview;
})

function templatePhoto(url, uiUpload) {

    return `<div class="span1" data-index="${uiUpload.currentIndex()}" data-name="${uiUpload.currentName()}">
                <div class="bui-upload-thumbnail"><img src="${url}" alt=""  style="width: 3rem;height: 3rem;object-fit: contain;"/><i class="icon-removefill"></i></div>
            </div>`
}
function templatePhotoDefault(url) {

    return `<div class="span1" data-index="-1" data-name="default.jpg">
                <div class="bui-upload-thumbnail"><img src="${url}" alt="" style="width: 3rem;height: 3rem;object-fit: contain;"/><i class="icon-removefill"></i></div>
            </div>`
}

function isWeiXin() {
    let ua = navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true
    } else {
        return false
    }
}
